#!/usr/bin/env python
# coding:utf-8
"""
Created on 2017/6/20 17:51

base Info
"""
__author__ = 'kumikoda'
__version__ = '1.0'

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import hashlib
import re
from modules import dbs
from modules import confs

class Users(object):
    '''docstring for user'''
    def __init__(self, phone=None, passwd=None, reg_info=None, remember=None):
        self.conn, self.cur = dbs.db_connect()
        self.phone = phone
        self.passwd = passwd
        self.reg_info = reg_info

    ## 用户是否存在
    def esxit_phone(self):
        query = "SELECT phone FROM user WHRER phone={phone} ".format(phone=self.phone)
        if self.cur.execute(query):
            return True # 用户存在
        else:
            return False # 用户不存在

    ## 查看用户状态
    def user_status(self):
        query = "SELECT status FROM user WHERE phone={phone} ".format(phone=self.phone)
        self.cur.execute(query)
        status = self.cur.fetchone()[0]
        if status == 1:
            return True # 用户激活
        else:
            return False # 用户未激活

    ## 验证密码
    def check_pass(self):
        query = "SELECT passwd FROM user WHERE phone={phone} ".format(phone=self.phone)
        self.cur.execute(query)
        dpasswd = self.cur.fetchone()[0] # 数据库取的密码
        self.cur.close()
        self.conn.close()
        self.passwd = hashlib.md5(self.passwd).hexdigest()
        if self.passwd == dpasswd:
            return True
        else:
            return False

    ## 登录
    def login(self):
        if not self.esxit_phone:
            result = {
                'code': 1,
                'message': confs._code.get(1, '用户不存在')
            }
            return result
        elif not self.user_status():
            result = {
                'code': 2,
                'message': confs._code.get(2, '用户未激活')
            }
            return result
        elif not self.check_pass():
            result = {
                'code': 3,
                'message': confs._code.get(3, '密码输入错误')
            }
            return result
        else:
            result = {
                'code': 0,
                'message': confs._code.get(0, '成功')
            }
            return result

    ## 判断信息完整度
    def check_reg_info(self):
        # 判断子集
        y = self.reg_info.keys()
        if 'phone' in y and 'passwd' in y and 'username' in y and 'mail' in y and 'en_mail' in y and 'en_passwd' in y:
            return True
        else:
            return False

    ## 判断用户手机正确性
    def check_phone(self):
        par = r'^1[3|4|5|7|8]\d{9}$'
        if re.match(par, self.phone):
            return True
        else:
            return False


    ## 判断用户提交的密码是否一致
    def check_enpasswd(self):
        if self.reg_info['passwd'] == self.reg_info['en_passwd']:
            return True
        else:
            return False

    ## 判断用户提交密码的长度
    def check_passwd_len(self):
        if len(self.reg_info['passwd']) >= 8:
            return True
        else:
            return False

    ## 注册
    def reg(self):
        self.phone = self.reg_info['phone']
        if self.esxit_phone:  # 如果存在，不允许注册
            result = {
                'code': 55,
                'message': confs._code.get(55, '手机号已存在，请更换手机号')
            }
            return result

        if not self.check_reg_info(): # 填写完整度
            result = {
                'code': 51,
                'message': confs._code.get(51, '请填写相应信息')
            }
            return result
        elif not self.check_phone():
            result = {
                'code': 52,
                'message': confs._code.get(52, '用户手机号不正确')
            }
            return result
        elif not self.check_enpasswd():
            result = {
                'code': 53,
                'message': confs._code.get(53, '密码不一致')
            }
            return result
        elif not self.check_passwd_len():
            result = {
                'code': 58,
                'message': confs._code.get(58, '密码小于8个字符')
            }
            return result
        else:
            passwd = hashlib.md5(self.reg_info['passwd']).hexdigest()
            query = '''
                            INSERT INTO user (
                                phone,
                                passwd,
                                mail,
                                en_mail,
                                username
                            )
                            VALUE
                                (
                                    '{phone}',
                                    '{passwd}',
                                    '{mail}',
                                    '{en_mail}',
                                    '{username}'
                                )
                        '''.format(phone=self.reg_info['phone'],
                                   passwd=passwd,
                                   mail=self.reg_info['mail'],
                                   en_mail=self.reg_info['en_mail'],
                                   username=self.reg_info['username'])
            try:
                self.cur.execute(query)
                self.conn.commit()
                self.cur.close()
                self.conn.close()
                result = {
                    'code': 0,
                    'message': '注册成功'
                }
                return result
            except Exception, e:
                result = {
                    'code': 54,
                    'message': str(e)
                }
                return result

    ## 查看用户信息
    def user_info(self):
        query = '''
        SELECT id,phone,username,mail,en_mail,status FROM user'''
        try:
            self.cur.execute(query)
            data = self.cur.fetchall()
            self.cur.close()
            self.conn.close()
            result = {
                'code': 0,
                'message': confs._code.get(0, '成功'),
                'result': {
                    'data': data
                }
            }
            return result
        except Exception, e:
            result = {
                'code': 56,
                'message': str(e)
            }

    def status_on(self, phone):
        query = "UPDATE user SET status=1 WHERE phone={phone} ".format(phone=phone)
        self.phone = phone
        print(query)
        try:
            if not self.check_phone():
                result = {
                    'code': 52,
                    'message': confs._code.get(52, '用户手机号不正确')
                }
                return result
            elif not self.esxit_phone:
                result = {
                    'code': 1,
                    'message': confs._code.get(1, '用户不存在')
                }
                return result
            else:
                print(query)
                self.cur.execute(query)
                self.conn.commit()
                self.cur.close()
                self.conn.close()
                result = {
                    'code': 0,
                    'message': confs._code.get(0, '成功')
                }
                return result

        except Exception, e:
            result = {
                'code': 57,
                'message': str(e)
            }
            return result

    def fetch_user(self, phone): # 查询用户
        query = "SELECT username,mail,en_mail FROM user WHERE phone={phone} ".format(phone=phone)
        print(query)
        try:
            self.cur.execute(query)
            data = self.cur.fetchone()
            result = {
                'code': 0,
                'message': 'success',
                'result': {
                    'data': data
                }
            }
            return result

        except Exception, e:
            result = {
                'code': 60,
                'message': confs._code(60, '查询用户失败')
            }
            return result

    def edit_user(self, username, phone, mail, en_mail, center, section_):  # 修改用户
            query = '''
                        UPDATE user
                        SET mail = '{mail}',
                         en_mail = {en_mail},
                         username = '{username}',
                         center = '{center}',
                         section_ = '{section_}'
                        WHERE
                            phone = {phone};
                    '''.format(mail=mail,
                               en_mail=en_mail,
                               phone=phone,
                               username=username,
                               center = center,
                               section_ = section_)
            try:
                self.cur.execute(query)
                self.conn.commit()
                result = {
                    'code': 0,
                    'message': '修改用户成功'
                }
                return result
            except Exception, e:
                result = {
                    'code': 59,
                    'message': str(e)
                }
                return result

if __name__ == '__main__':
    # 用户注册测试
    #register_info = {
    #    'phone': '13678978585',
    #    'username': 'ayumi',
    #    'passwd': 'p@ssw0rd',
    #    'mail': '449269579@qq.com',
    #    'en_mail': '449269579@qq.com',
    #    'en_passwd': 'p@ssw0rd'
    #}

    #u = Users(reg_info=register_info)
    #result = u.reg()
    #print(result)
    #print(result['message'])


    # user login test
    u = Users(phone=13434111885, passwd='p@ssw0rd')
    result = u.login()
    print(result)
    print(result['message'])